//
//  EFAMsgCfgVC.m
//  efairy
//  设备配置功能
//  Created by XiangDongMBP on 2017/8/29.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAMsgCfgVC.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "EFAModel.h"
#import "UIColor+XDHex.h"
#import "EFAUtySelCommonVC.h"
#define NUMBERS @"0123456789"

@interface EFAMsgCfgVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource,UITextFieldDelegate>
@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) UIBarButtonItem *saveBarBtnItem;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) EFADeviceCfgModel *cfgModel;
@property (strong, nonatomic) NSArray *titleArray;
@property (strong, nonatomic) UIAlertAction *secureTextAlertAction;
@end

static NSString *const kReuseCellId = @"UITableViewCell";
//static NSInteger const kRequestUserSize = 20;

@implementation EFAMsgCfgVC
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"配置信息";
    self.navigationItem.rightBarButtonItem = self.saveBarBtnItem;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
//    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
//    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
//    self.tableView.mj_header = self.mj_header;
//    self.tableView.mj_footer = self.mj_footer;
    
//    [self.tableView.mj_header beginRefreshing];
    [self requestDeviceCfgWithHeader:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"没有数据" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    //    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
    return nil;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return 1;
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cfgModel ? self.cfgModel.efairydevicesetting_thv_list.count : 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kReuseCellId];
        cell.textLabel.font = [UIFont systemFontOfSize:14.0];
        cell.textLabel.textColor = [UIColor xd_colorWithHex:EFAGlobalColorFontDarkBlack];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:14.0];
        cell.detailTextLabel.textColor = [UIColor xd_colorWithHex:EFAGlobalColorFontMidBlack];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
//    NSArray *value = @[[NSString stringWithFormat:@"%ldS", (long)self.cfgModel.efairydevicesetting_heartbeat_interval],
//                       [NSString stringWithFormat:@"%@", self.cfgModel.efairydevicesetting_audio_on ? @"正常" : @"静音"]];
//    if (indexPath.row < value.count) {
//        cell.textLabel.text = self.titleArray[indexPath.row];
//        cell.detailTextLabel.text = value[indexPath.row];
//    } else {
//        NSInteger index = indexPath.row - value.count;
//        if (index < self.cfgModel.efairydevicesetting_thv_list.count) {
    EFADevRealTimeDataItem *item = self.cfgModel.efairydevicesetting_thv_list[indexPath.row];
//            cell.textLabel.text = [NSString stringWithFormat:@"%@通道%ld报警阈值", item.cidTitle, (long)item.cidDisplay];
    cell.textLabel.text = item.c_name;
    if(item.cid == -10){
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%0.0f%@",item.thv,item.unit];
    }else if(item.cid == -20){
        cell.detailTextLabel.text = item.thv == 0?@"静音":@"正常";
    }else if(item.value_type == 2){
        //配置方式为选择模式，包括检测通道等
        for(int i = 0; i<item.value_range.count; i++){
            if(item.value_range[i].value == item.thv){
                cell.detailTextLabel.text = item.value_range[i].name;
                break;
            }
        }
    }else{
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%0.1f%@",item.thv,item.unit];
    }
    
//        }
//    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5.9;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
//    if (indexPath.row == 0) {   // 心跳间隔
//        [self jumpToSelectHeartBeat];
//    } else
//     if (indexPath.row == 1) {    // 音响模式
//        [self jumpToSelectMuteMode];
//     } else {
//        NSInteger index = indexPath.row - self.titleArray.count;
//        if (index < self.cfgModel.efairydevicesetting_thv_list.count) {
//            EFADevRealTimeDataItem *item = self.cfgModel.efairydevicesetting_thv_list[indexPath.row];
//            [self jumpToSelectPtThv:item];
//            [self inputDeviceThv:item];
//        }
//    }
    EFADevRealTimeDataItem *item = self.cfgModel.efairydevicesetting_thv_list[indexPath.row];
    if(item.cid == -20 || item.value_type == 2){
        [self jumpToSelectMuteMode:item];
    }else{
         [self inputDeviceThv:item];
    }
   
}

#pragma mark - 保存数据，方法在上设备聊天界面
- (void)saveBarBtnTapped:(UIBarButtonItem *)item {
    [self.cfgModel.efairydevicesetting_thv_list removeObjectAtIndex:0];
    [self.cfgModel.efairydevicesetting_thv_list removeObjectAtIndex:0];
    if (self.successHandle) {
        self.successHandle(self.cfgModel);
        self.successHandle = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - private methods
- (void)jumpToSelectHeartBeat {
    EFAUtySelCommonVC *vc = [[EFAUtySelCommonVC alloc] initWithStart:30 end:240 unit:@"S" containsZero:NO];
    vc.successHandle = ^(NSInteger selValue) {
        self.cfgModel.efairydevicesetting_heartbeat_interval = selValue;
        [self refreshWholeView];
    };
    [self presentViewController:vc animated:YES completion:nil];
}
#pragma mark - 音响模式和选择模式设置方法
- (void)jumpToSelectMuteMode:(EFADevRealTimeDataItem *)item {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:item.c_name message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    if(item.cid==-20){
        [alertVC addAction:[UIAlertAction actionWithTitle:@"静音" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.cfgModel.efairydevicesetting_audio_on = 0;
            item.thv = 0;
            [self refreshWholeView];
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"正常" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.cfgModel.efairydevicesetting_audio_on = 1;
            item.thv = 1;
            [self refreshWholeView];
        }]];
    }else{
        for(int i = 0; i<item.value_range.count;i++){
            [alertVC addAction:[UIAlertAction actionWithTitle:item.value_range[i].name style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                item.thv = item.value_range[i].value;
                [self refreshWholeView];
            }]];
        }
    }
   
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

//已废弃
- (void)jumpToSelectPtThv:(EFADevRealTimeDataItem *)item {
    if ([[EFADeviceProtocolModel sharedInstance] isSwitchPt:item.pt]) {
        NSArray<NSNumber *> *keys = [[EFADeviceProtocolModel sharedInstance] thvRangeArrayWithPt:item.pt];
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:item.cidTitle message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        for (NSNumber *keyItem in keys) {
            NSString *thvValueStr = [[EFADeviceProtocolModel sharedInstance] thvSwitchDescribeWithThv:keyItem.integerValue pt:item.pt];
            [alertVC addAction:[UIAlertAction actionWithTitle:thvValueStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                item.thv = keyItem.integerValue;
                [self refreshWholeView];
            }]];
        }
        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alertVC animated:YES completion:nil];
    } else {
        EFAUtySelCommonVC *vc = [[EFAUtySelCommonVC alloc] initWithStart:item.thvStart end:item.thvEnd unit:item.ptUnit containsZero:YES];
        vc.successHandle = ^(NSInteger selValue) {
            [item configThv:selValue];
            [self refreshWholeView];
        };
        [self presentViewController:vc animated:YES completion:nil];
    }
}

//验证是否输入值
- (void)handleTextFieldTextDidChangeNotification:(NSNotification *)notification {
    UITextField *textField = notification.object;
    // Enforce a minimum length of >= 5 characters for secure text alerts.
    self.secureTextAlertAction.enabled = textField.text.length > 0;
}

-(void)inputDeviceThv:(EFADevRealTimeDataItem *)item{
    NSMutableArray<ValueRange *> *mArray = item.value_range;
    if(mArray && mArray.count > 1){
        if([mArray[0].name isEqualToString:@"min"]){
            item.min = mArray[0].value;
        }else{
            item.max = mArray[0].value;
        }
        if([mArray[1].name isEqualToString:@"min"]){
            item.min = mArray[1].value;
        }else{
            item.max = mArray[1].value;
        }
    }
    NSString *nsstr = [NSString stringWithFormat:@"提示：最小阈值%lu%@，最大阈值%lu%@",item.min,item.unit,item.max,item.unit];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nsstr message:@"" preferredStyle:UIAlertControllerStyleAlert];
    
    //增加取消按钮；
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    
    //增加确定按钮；
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        //移除通知
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:alertController.textFields.firstObject];
        
        CGFloat tValue =  [alertController.textFields.firstObject.text floatValue];
        if(tValue < item.min){
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:[NSString stringWithFormat:@"阈值不能小于%lu",item.min]];
//            [self presentViewController:alertController animated:YES completion:nil];
            return;
        }else if(tValue > item.max){
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:[NSString stringWithFormat:@"阈值不能大于%lu",item.max]];
//            [self presentViewController:alertController animated:YES completion:nil];
            return ;
        }else{
            //获取内容
            if(item.cid == -10){
                self.cfgModel.efairydevicesetting_heartbeat_interval = tValue;
            }
            item.thv = tValue;
            [self refreshWholeView];
        }
        
    }];
    [alertController addAction:otherAction];
    otherAction.enabled = NO;
    self.secureTextAlertAction = otherAction;
    
    //定义第一个输入框；
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入阈值";
        //添加通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:textField];
        textField.delegate = self;
//        textField.secureTextEntry = YES;
    }];
    //这里是获取title和message
//    UIView *subView1 = alertController.view.subviews[0];
//    UIView *subView2 = subView1.subviews[0];
//    UIView *subView3 = subView2.subviews[0];
//    UIView *subView4 = subView3.subviews[0];
//    UIView *subView5 = subView4.subviews[0];
//    NSLog(@"subview4:%@",subView4.subviews);
//    NSLog(@"subview5:%@",subView5.subviews);
    //取title和message：在真机iphone5上title是 subView5.subviews[0]; message是subView5.subviews[1]; 我在模拟器上是subviews[1]和subviews[2]
//    UILabel *title = subView5.subviews[1];
//    UILabel *message = subView5.subviews[2];
//    message.textAlignment = NSTextAlignmentLeft;
//    title.textAlignment = NSTextAlignmentLeft;
    
    
    //修改title
    NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:nsstr];
//    [alertControllerStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
    [alertControllerStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10] range:NSMakeRange(0, nsstr.length)];
    [alertController setValue:alertControllerStr forKey:@"attributedTitle"];
    
    //修改message
    if(item.cid != -10){
        NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:@"关闭通道阈值请设置0"];
        [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 10)];
        [alertControllerMessageStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10] range:NSMakeRange(0, 10)];
        [alertController setValue:alertControllerMessageStr forKey:@"attributedMessage"];
    }
 
    [self presentViewController:alertController animated:true completion:nil];
}


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet];
    
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
    
    BOOL canChange = [string isEqualToString:filtered];
    
    //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
    if (range.length == 1 && string.length == 0) {
        return  canChange && YES;
    }else if (textField.text.length >= 6) {
        textField.text = [textField.text substringToIndex:6];
        return NO;
    }
    
    return canChange;
}



- (void)refreshWholeView {
    //    // 尾部加载更多的显示
    //    if (self.userList.totalLoad) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestDeviceCfgWithHeader:isHeader];
    
//    [self tableViewEndRefresh:isHeader];
//    [self refreshWholeView];
}
#pragma mark - network request 请求数据
- (void)requestDeviceCfgWithHeader:(BOOL)isHeader {
    // 需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairydevice_id" : @(self.device_id)};
    NSLog(@"请求设备配置的参数：%@", pars);
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiDeviceSetting] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求设备配置返回：%@", responseObject);
        [hud hideAnimated:YES];
        self.cfgModel = [EFADeviceCfgModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        EFADevRealTimeDataItem *heartbeatInterval = [[EFADevRealTimeDataItem alloc]init];
        heartbeatInterval.cid =  -10; //自己定义代表是心跳间隔
        heartbeatInterval.min = 30;
        heartbeatInterval.max = 240;
        heartbeatInterval.unit = @"S";
        heartbeatInterval.c_name = @"心跳间隔";
        //心跳间隔  服务端返回的数据
        heartbeatInterval.thv =self.cfgModel.efairydevicesetting_heartbeat_interval;
        
        EFADevRealTimeDataItem *audioOn = [[EFADevRealTimeDataItem alloc]init];
        audioOn.cid =  -20;//自己定义代表是音响模式
        audioOn.min = 30;
        audioOn.max = 240;
        audioOn.unit = @"S";
        audioOn.c_name = @"音响模式";
        //心跳间隔  服务端返回的数据
        audioOn.thv =self.cfgModel.efairydevicesetting_audio_on;//0静音：1正常
        
        [ self.cfgModel.efairydevicesetting_thv_list insertObject:audioOn atIndex:0];
        [ self.cfgModel.efairydevicesetting_thv_list insertObject:heartbeatInterval atIndex:0];
       
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求设备配置失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - 保存按钮
- (UIBarButtonItem *)saveBarBtnItem {
    if (!_saveBarBtnItem) {
        _saveBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_saveBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_saveBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _saveBarBtnItem;
}

- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}
- (NSArray *)titleArray {
    if (!_titleArray) {
        _titleArray = @[@"心跳间隔", @"音响模式"];
    }
    return _titleArray;
}
@end
